package com.maori.languageapp.usermanager;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.maori.languageapp.LanguageAppCaptureActivity;
import com.maori.languageapp.R;
import com.maori.languageapp.UploadToFtp;

public class Languageapp_Register_New_User extends Activity {
	Button canceluserregister, submituserregister, camera_button,
			gallery_button;
	EditText etfirst_name, etlast_name, ettribe, etemail, etusername,
			etpassword, etpasswordconfirm, etrole, userlocation;
	private Uri fileUri;
	private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
	public static final int MEDIA_TYPE_IMAGE = 1;
	public static final int MEDIA_TYPE_VIDEO = 2;
	protected static final String TAG = null;
	private static final String IMAGE_DIRECTORY_NAME = "lANGUAGEAPP";
	static String upladingFromPath, sourceUrl;
	static String filename = "404";
	private static final int PICK_IMAGE = 1;
	ImageView ivThumbnailPhoto;
	Uri selectedImageUri;
	byte[] data;
	String filemanagerstring, tempDir;
	String selectedImagePath;
	String filePath;
	private Bitmap bitmap;
	String currentImageName = "1";
	String desDirectory = "http://langapp.testarea.co.nz:2082/lanappimage/";
	ProgressDialog mProgressDialog;
	HttpParams httpParameters = new BasicHttpParams();
	int timeoutConnection = 5000;
	InputStream is = null;
	StringBuilder sb = null;
	String result = null;
	String StrUserRole;
	JSONArray jsonarray;
	ArrayList<HashMap<String, String>> arraylist;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);

		// setContentView(R.layout.maori_login);
		setContentView(R.layout.languageapp_register_new_user);

		submituserregister = (Button) findViewById(R.id.submitbtn);
		canceluserregister = (Button) findViewById(R.id.cancelbtn);
		camera_button = (Button) findViewById(R.id.camera_button);
		gallery_button = (Button) findViewById(R.id.gallery_button);

		etfirst_name = (EditText) findViewById(R.id.etfirst_name);
		etlast_name = (EditText) findViewById(R.id.etlast_name);
		ettribe = (EditText) findViewById(R.id.ettribe);
		etemail = (EditText) findViewById(R.id.etemail);
		etusername = (EditText) findViewById(R.id.etemail);
		etpassword = (EditText) findViewById(R.id.etpassword);
		etpasswordconfirm = (EditText) findViewById(R.id.etpasswordconfirm);
		userlocation = (EditText) findViewById(R.id.etuserlocation);
		//etrole = (EditText) findViewById(R.id.etrole);

		submituserregister.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				if(etemail.getText().toString().length() == 0){
					showAlertDialog(Languageapp_Register_New_User.this,
							"Invalid Email",
							"Please Enter Valid Email...", false);
				}
				else if(etpassword.getText().toString().length() == 0){
					showAlertDialog(Languageapp_Register_New_User.this,
							"Invalid Password",
							"Please Enter Password...", false);
				}
				else if(etpassword.getText().toString().equals(etpasswordconfirm.getText().toString())){
					if (isNetworkAvailable()) {
						new UploadTask().execute();

					} else {
						showAlertDialog(Languageapp_Register_New_User.this,
								"No Internet Connection",
								"You don't have internet connection...", false);
					}
				}
				else{
					showAlertDialog(Languageapp_Register_New_User.this,
							"Invalid Password",
							"Password Mismatch. Please Check Again...", false);
				}
				
				
			}
		});

		canceluserregister.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				onBackPressed();
			}
		});

		camera_button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				// create intent with ACTION_IMAGE_CAPTURE action
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

				Log.v(TAG, "PRINT _ 1: " + fileUri);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
				// start the image capture Intent
				startActivityForResult(intent,
						CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
			}
		});

		// Launch Camera
		ivThumbnailPhoto = (ImageView) findViewById(R.id.ImageView01);
		camera_button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				// create intent with ACTION_IMAGE_CAPTURE action
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

				Log.v(TAG, "PRINT _ 1: " + fileUri);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
				// start the image capture Intent
				startActivityForResult(intent,
						CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
			}
		});

		gallery_button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				try {
					Intent intent = new Intent();
					intent.setType("image/*");
					intent.setAction(Intent.ACTION_GET_CONTENT);
					startActivityForResult(
							Intent.createChooser(intent, "Select Picture"),
							PICK_IMAGE);

				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), e.getMessage(),
							Toast.LENGTH_LONG).show();
					Log.e(e.getClass().getName(), e.getMessage(), e);
				}

			}
		});
		
		
		
	}
	
	
	public void onRadioButtonClicked(View view) {
	    // Is the button now checked?
	    boolean checked = ((RadioButton) view).isChecked();
	    
	    // Check which radio button was clicked
	    switch(view.getId()) {
	        case R.id.radio_standard:
	            if (checked)
	            	 //Toast.makeText(this, "Standard", Toast.LENGTH_LONG).show();
	            	StrUserRole = "Standard";
	            break;
	        case R.id.radio_expert:
	            if (checked)
	            	//Toast.makeText(this, "Expert", Toast.LENGTH_LONG).show();
	            	StrUserRole = "Expert";
	            break;
	    }
	}

	public boolean isNetworkAvailable() {
		ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			return false;
		} else {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}

	// ************************M1************************
	/**
	 * Receiving activity result method will be called after closing the camera
	 * */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// if the result is capturing Image
		if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				// successfully captured the image
				// display it in image view
				previewCapturedImage();
			} else if (resultCode == RESULT_CANCELED) {
				// user cancelled Image capture
				Toast.makeText(getApplicationContext(),
						"User cancelled image capture", Toast.LENGTH_SHORT)
						.show();
			} else {
				// failed to capture image
				Toast.makeText(getApplicationContext(),
						"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
						.show();
			}
		} else if (resultCode == Activity.RESULT_OK) {
			if (resultCode == Activity.RESULT_OK) {
				selectedImageUri = data.getData();
				Log.e("Bitmap", "selectedImageUri :" + selectedImageUri);
				try {
					// OI FILE Manager
					filemanagerstring = selectedImageUri.getPath();

					// MEDIA GALLERY
					selectedImagePath = getPath(selectedImageUri);

					if (selectedImagePath != null) {
						filePath = selectedImagePath;
					} else if (filemanagerstring != null) {
						filePath = filemanagerstring;
					} else {
						Toast.makeText(getApplicationContext(), "Unknown path",
								Toast.LENGTH_LONG).show();
						Log.e("Bitmap", "Unknown path");
					}

					if (filePath != null) {
						decodeFile(filePath);
					} else {
						bitmap = null;
					}
				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), "Internal error",
							Toast.LENGTH_LONG).show();
					Log.e(e.getClass().getName(), e.getMessage(), e);
				}
			}
		}

	}

	private boolean prepareDirectory() {
		try {
			if (makedirs()) {
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(
					this,
					"Could not initiate File System.. Is Sdcard mounted properly?",
					Toast.LENGTH_SHORT).show();
			return false;
		}
	}

	private boolean makedirs() {
		File tempdir = new File(tempDir);
		if (!tempdir.exists())
			tempdir.mkdirs();

		if (tempdir.isDirectory()) {

		}
		return (tempdir.isDirectory());
	}

	private String decodeFile(String filePath) {
		// Decode image size
		BitmapFactory.Options o = new BitmapFactory.Options();
		o.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filePath, o);

		// The new size we want to scale to
		final int REQUIRED_SIZE = 1024;

		// Find the correct scale value. It should be the power of 2.
		int width_tmp = o.outWidth, height_tmp = o.outHeight;
		int scale = 1;
		while (true) {
			if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
				break;
			width_tmp /= 2;
			height_tmp /= 2;
			scale *= 2;
		}

		BitmapFactory.Options o2 = new BitmapFactory.Options();
		o2.inSampleSize = scale;

		bitmap = BitmapFactory.decodeFile(filePath, o2);
		ivThumbnailPhoto.setImageBitmap(bitmap);

		Calendar c = Calendar.getInstance();
		SimpleDateFormat dfsigdate = new SimpleDateFormat("yyyyMMddHHmmss");
		String formattedSigDatep = dfsigdate.format(c.getTime());
		tempDir = "/data/data/com.maori.languageapp/CAMIMAGES/";
		Log.v(TAG, "XXX tempDir : " + tempDir);
		prepareDirectory();
		String filenamepath = tempDir + getAudiorecording().toString() + ".png";
		currentImageName = getAudiorecording().toString() + ".png";

		Log.v(TAG, "XXX tempDir : " + filenamepath);
		File dest = new File(filenamepath);
		try {
			FileOutputStream out = new FileOutputStream(dest);
			bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			Log.v(TAG, "Exception : " + e);
		}

		return filePath;
	}

	private String getPath(Uri selectedImageUri) throws FileNotFoundException {

		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(selectedImageUri, projection, null, null,
				null);

		if (cursor != null) {

			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

			cursor.moveToFirst();
			/* Uri uri = Uri.parse(cursor.getString(1)); */

			return cursor.getString(column_index);
		} else
			return null;
	}

	// ====================================
	private byte[] getByteArrayFromImage(String filePath)
			throws FileNotFoundException, IOException {

		File file = new File(filePath);
		System.out.println(file.exists() + "!!");

		FileInputStream fis = new FileInputStream(file);
		// create FileInputStream which obtains input bytes from a file in a
		// file system
		// FileInputStream is meant for reading streams of raw bytes such as
		// image data. For reading streams of characters, consider using
		// FileReader.

		// InputStream in = resource.openStream();
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] buf = new byte[1024];
		try {
			for (int readNum; (readNum = fis.read(buf)) != -1;) {
				bos.write(buf, 0, readNum);
				// no doubt here is 0
				/*
				 * Writes len bytes from the specified byte array starting at
				 * offset off to this byte array output stream.
				 */
				System.out.println("read " + readNum + " bytes,");
			}
		} catch (IOException ex) {
			Log.d("error", "error");
		}
		byte[] bytes = bos.toByteArray();
		return bytes;
	}

	/**
	 * ------------ Helper Methods ----------------------
	 * */

	public void openPath(Uri uri) {
		InputStream is = null;
		try {
			is = getContentResolver().openInputStream(uri);

			// Convert your stream to data here
			is.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/*
	 * Creating file uri to store image/video
	 */
	public Uri getOutputMediaFileUri(int type) {
		return Uri.fromFile(getOutputMediaFile(type));
	}

	/*
	 * returning image / video
	 */
	private static File getOutputMediaFile(int type) {

		// External sdcard location
		File mediaStorageDir = new File(
				Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
				IMAGE_DIRECTORY_NAME);
		Log.v(TAG, "PRINT _ 4: " + mediaStorageDir);
		upladingFromPath = mediaStorageDir.getAbsolutePath();
		// Create the storage directory if it does not exist
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
						+ IMAGE_DIRECTORY_NAME + " directory");
				return null;
			}
		}

		// Create a media file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
				Locale.getDefault()).format(new Date());
		File mediaFile;
		if (type == MEDIA_TYPE_IMAGE) {
			mediaFile = new File(mediaStorageDir.getPath() + File.separator
					+ "IMG_" + timeStamp + ".jpg");
			filename = "IMG_" + timeStamp + ".jpg";
			sourceUrl = mediaFile.toString();
			Log.v(TAG, "PRINT _ 5: " + filename);
			Log.v(TAG, "PRINT _ 6: " + sourceUrl);

		} else if (type == MEDIA_TYPE_VIDEO) {
			mediaFile = new File(mediaStorageDir.getPath() + File.separator
					+ "VID_" + timeStamp + ".mp4");
			Log.v(TAG, "PRINT _ 7: " + mediaFile);
		} else {
			return null;
		}

		return mediaFile;
	}

	/*
	 * Display image from a path to ImageView
	 */
	private void previewCapturedImage() {
		try {
			// hide video preview
			// videoPreview.setVisibility(View.GONE);

			ivThumbnailPhoto.setVisibility(View.VISIBLE);

			// bimatp factory
			BitmapFactory.Options options = new BitmapFactory.Options();

			// downsizing image as it throws OutOfMemory Exception for larger
			// images
			options.inSampleSize = 8;

			final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
					options);
			ivThumbnailPhoto.setImageBitmap(bitmap);
			Log.v(TAG, "PRINT _ PREVIEW 1 : " + fileUri.getPath());

		} catch (NullPointerException e) {
			e.printStackTrace();
		}
	}

	private String getAudiorecording() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyyMMddHHmmss");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	class UploadTask extends AsyncTask<Void, Void, Void> {

		ProgressDialog pDialog;
		Boolean uploadStat;

		@Override
		protected void onPreExecute() {
			mProgressDialog = new ProgressDialog(
					Languageapp_Register_New_User.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Register");
			// Set progressdialog message
			mProgressDialog.setMessage("Register New User");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();
			/*pDialog = new ProgressDialog(Languageapp_Register_New_User.this);
			pDialog.setMessage("Uploading Image Files...");
			pDialog.show();*/
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// /Pictures/lANGUAGEAPP
			upladingFromPath = "/storage/emulated/0/Pictures/lANGUAGEAPP/";
			Log.v(TAG, "data uploading 1 : " + upladingFromPath);
			Log.v(TAG, "data uploading 2 : " + filename);
			Log.v(TAG, "data uploading 3 : " + desDirectory);

			uploadStat = new UploadToFtp().ftpUpload1(upladingFromPath,
					filename, desDirectory);
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					if (uploadStat) {

					} else {
						AlertDialog.Builder b = new AlertDialog.Builder(
								Languageapp_Register_New_User.this);
						b.setMessage("Upload Failed.");
						b.show();
					}

				}
			});
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			if (null != pDialog && pDialog.isShowing()) {
				pDialog.dismiss();
			}
			super.onPostExecute(result);
			new UploadingWordsDetails().execute();

		}
	}

	private class UploadingWordsDetails extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
		}
		//usermanager
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpPost httppost = null;
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				httppost = new HttpPost("http://langapp.mirzabros.com/maoriapi/usermanager/registernewuser.php");
				
				JSONObject json = new JSONObject();
				// etfirst_name,etlast_name,ettribe,etemail,etusername,etpassword,etpasswordconfirm,etrole;
				json.put("record1", etfirst_name.getText().toString());
				json.put("record2", etlast_name.getText().toString());
				json.put("record3", ettribe.getText().toString());
				json.put("record4", etemail.getText().toString());
				json.put("record5", etusername.getText().toString());
				json.put("record6", etpassword.getText().toString());
				json.put("record7", userlocation.getText().toString());
				json.put("record8", StrUserRole);
				json.put("record9", getAudiorecording().toString());
				json.put("record10", "1");
				json.put("record11",
						"http://langapp.mirzabros.com/lanappimage/" + filename);
				JSONArray postjson = new JSONArray();
				postjson.put(json);

				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				Log.e("postjson", "postjson :" + postjson.toString());

				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					
				}
			} catch (Exception e) {

			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			mProgressDialog.dismiss();
			
			if (result != null) {
				arraylist = new ArrayList<HashMap<String, String>>();
				try {
					JSONObject jsonObj = new JSONObject(result);
					jsonarray = jsonObj.getJSONArray("posts");
					for (int i = 0; i < jsonarray.length(); i++) {
						JSONObject c = jsonarray.getJSONObject(i);
						String RegisterState = c.getString("RegisterState");
						if(RegisterState.equals("RegisteredUser")){
							final AlertDialog alertDialog = new AlertDialog.Builder(
									Languageapp_Register_New_User.this).create();
							// Setting Dialog Title
							alertDialog.setTitle("REGISTER FAIL");
							// Setting Dialog Message
							alertDialog.setMessage("User Registration Not Completed. Current User Already Registered..");
							// Setting OK Button
							alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int which) {
									onBackPressed();
									alertDialog.dismiss();
								}
							});
							// Showing Alert Message
							alertDialog.show();
							alertDialog.setCanceledOnTouchOutside(false);
							return;
						}
						else if(RegisterState.equals("RegisteredNew")){
							final AlertDialog alertDialog = new AlertDialog.Builder(
									Languageapp_Register_New_User.this).create();
							// Setting Dialog Title
							alertDialog.setTitle("REGISTER SUCCESS");
							// Setting Dialog Message
							alertDialog.setMessage("User Registration Completed...");
							// Setting OK Button
							alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int which) {
									onBackPressed();
									alertDialog.dismiss();
								}
							});
							// Showing Alert Message
							alertDialog.show();
							alertDialog.setCanceledOnTouchOutside(false);
							return;
						}
						
						
						
					}
				}
				catch(Exception e){
					
				}
			}
		}
	}
	// Display Network connection Fail Alert
		public void showAlertDialog(Context context, String title, String message,
				Boolean status) {
			final AlertDialog alertDialog = new AlertDialog.Builder(context)
					.create();

			// Setting Dialog Title
			alertDialog.setTitle(title);

			// Setting Dialog Message
			alertDialog.setMessage(message);

			// Setting alert dialog icon
			alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					// new DownloadAdministrative().execute();
					alertDialog.dismiss();
				}
			});

			// Showing Alert Message
			alertDialog.show();
		}
}
